package com.limao.CacheManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.limao.Model.ImagerUrls;
import com.limao.Model.LzPluginException;
import com.limao.Model.PublicData;
import com.limao.Tool.CacheClass;
import com.limao.Tool.Function;
import com.limao.Utils.OSSObjectSample;

public class UploadInfo {
	
	private static String[] FilTpye = { "jpg", "jpeg", "png", "amr", "mp3" };
	private static long MaxFileSize = 1024 * 1024 * 3;
	
	
	public static Object UploadFile(HttpServletRequest request,AsyncContext asyncContext) throws LzPluginException, Exception
	{

		PublicData jsonObj = new PublicData();

		request.setCharacterEncoding("UTF-8");

		// 创建文件处理工厂，它用于生成FileItem对象。
		DiskFileItemFactory difactory = new DiskFileItemFactory();
		// 设置缓存大小，如果上传文件超过缓存大小，将使用临时目录做为缓存。
		difactory.setSizeThreshold(1024 * 1024);
		// 设置处理工厂缓存的临时目录，此目录下的文件需要手动删除。
		//String dir = sc.getRealPath("/");
	
		String dir=new File(System.getProperty("catalina.home")).toString()+File.separator+"webapps"+File.separator;
		
		File filedir = new File(dir + Function.myFiles);
		if (!filedir.exists())
			filedir.mkdir();
		difactory.setRepository(filedir);
		
		// 创建request的解析器，它会将数据封装到FileItem对象中。
		ServletFileUpload sfu = new ServletFileUpload(difactory);
		sfu.setFileSizeMax(MaxFileSize);// 单个文件的最大size
		// 解析保存在request中的数据并返回list集合
		List list = sfu.parseRequest(request);

		if (list != null) {
			int uploadFilenum = 0;
			int sucussFilenum = 0;
			ImagerUrls URLList = new ImagerUrls();
            System.out.println("hhhhhhh");
			// 遍历list集合，取出每一个输入项的FileItem对象，并分别获取数据
			for (Iterator it = list.iterator(); it.hasNext();) {
				FileItem fi = (FileItem) it.next();
				if (fi.isFormField()) {// 表单的参数字段

				} else
				{
					uploadFilenum = uploadFilenum + 1;
					// 由于客户端向服务器发送的文件是客户端的全路径，在这我们只需要文件名即可
					if (fi.getName() != null && !fi.getName().equals(""))// 一个上传的文件
					{
						String ddFile = fi.getFieldName();
						System.out.println("文件的名称：" + fi.getName());
						System.out.println("文件的大小：" + fi.getSize());
						System.out.println("文件的类型：" + fi.getContentType());
						String filename = fi.getName();

						int index = filename.lastIndexOf("\\");
						if (index != -1)
							filename = filename.substring(index + 1);
						if (!FileType(filename, fi.getSize()))// 上传的文件类型与大小										// 检测
						{
							throw new LzPluginException("文件类型不对或文件超过1M ");
						} else {
							// 向服务器写出文件
							String dd=null;
							InputStream in = null;
							try {
								in = fi.getInputStream();
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
							if(CacheClass.isOut==0)//外网运营图片上传
							{
								String newFileNmae=hashNewFile(fi.getName());
								boolean falg;
								try {
									//外网上传图片
							    falg =	OSSObjectSample.OSS_upload(in, newFileNmae, fi.getSize(), fi.getContentType());
							    
							    if(falg){
							    	dd=newFileNmae;
							    	System.out.println("文件名：" + newFileNmae);
							    }
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									dd=null;
						        } finally 
						        {
						        	if (in != null)
										try {
											in.close();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
						        }
							} else if(CacheClass.isOut==1)//外网测试图片上传
							{
								String newFileNmae=hashNewFile(fi.getName());
								boolean falg;
								try {
									//外网上传图片
							    falg =	OSSObjectSample.OSS_upload(in, newFileNmae, fi.getSize(), fi.getContentType());
							    
							    if(falg){
							    	dd=newFileNmae;
							    	System.out.println("文件名：" + newFileNmae);
							    }
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									dd=null;
						        } finally 
						        {
						        	if (in != null)
										try {
											in.close();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
						        }
							}
							else
							{   //内网上传的图片
	
								// 设置文件实际保存的目录
								System.out.println("上传路径="+dir);
								if (!dir.endsWith("\\") || !dir.endsWith("\\")) {
									dir += "\\";
								}
						        for(int i=0;i<3;i++)
						        {
						        	dir=dir.substring(0, dir.lastIndexOf("\\"));
						        	System.out.println("上传路径="+i+dir);
						        }
						        if (!dir.endsWith("\\")) {
						        	dir += "\\";
						        } 
									
								String userdir = dir + Function.myFiles;
								
								File fudir = new File(userdir);
								if (!fudir.exists())
									fudir.mkdir();
								
								String PathFile[] = hashPath(userdir, filename);								
								FileOutputStream fos = new FileOutputStream(PathFile[0]);
								byte[] buf = new byte[1024];
								int len = -1;
								while ((len = in.read(buf)) != -1) {
									fos.write(buf, 0, len);
								}

								// 关闭流
								if (in != null) {
									in.close();
									if (fos != null)
										fos.close();
								}
								dd = Function.myFiles + PathFile[1];
							}
							if(dd==null)
							{
								throw new LzPluginException("上传失败！ ");
							}

							switch (sucussFilenum) {
							case 0:
								URLList.IMAGE0 = dd;
								break;
							case 1:
								URLList.IMAGE1 = dd;
								break;
							case 2:
								URLList.IMAGE2 = dd;
								break;
							case 3:
								URLList.IMAGE3 = dd;
								break;
							case 4:
								URLList.IMAGE4 = dd;
								break;
							case 5:
								URLList.IMAGE5 = dd;
								break;
							case 6:
								URLList.IMAGE6 = dd;
								break;
							case 7:
								URLList.IMAGE7 = dd;
								break;
							case 8:
								URLList.IMAGE8 = dd;
								break;
							case 9:
								URLList.IMAGE9 = dd;
								break;
							default:
								sucussFilenum = 0;
							}
							sucussFilenum = sucussFilenum + 1;
						}

					}

				
				}
			}
			// 返回数据
			if (uploadFilenum == 0) {
				jsonObj.state = "0";
				jsonObj.info = "没有选择上传文件！";
				return jsonObj;
			} else if (sucussFilenum == uploadFilenum) {
				System.out.println("成功！");
				System.out.println(URLList.IMAGE0);
				
				jsonObj.state = "1";
				jsonObj.info = "成功！";
				jsonObj.URLList = URLList;
				return jsonObj;

			} else {
				throw new LzPluginException("上传失败！ ");
			}
		}
		return null;
	}
	
	


	private static boolean FileType(String filename, long size) {
		boolean tmp = false;
		if (size > MaxFileSize)
			return tmp;
		String extraFile = filename.substring((filename.lastIndexOf(".") + 1));
		for (int i = 0; i < FilTpye.length; i++) {
			if (extraFile.equalsIgnoreCase(FilTpye[i])) {
				tmp = true;
				break;
			}
		}
		return tmp;
	}
	
	private boolean isPicFileType(String filename, long size) {
		boolean tmp = false;
		String extraFile = filename.substring((filename.lastIndexOf(".") + 1));
		if(extraFile.equalsIgnoreCase("jpg") || extraFile.equalsIgnoreCase("jpeg") || extraFile.equalsIgnoreCase("png") )//"jpg", "jpeg", "png"
			tmp = true;
		return tmp;
	}


	// 生成唯一性名称的文件名
	private static String uuidName(String fileName) {
		UUID uuid = UUID.randomUUID();
		fileName = fileName.substring((fileName.lastIndexOf(".") ));
		return uuid.toString() + "_" + fileName;
	}

	// 目录结构生成算法 [0]绝对路径 [1]相对路径
	public static String[] hashPath(String dir, String fileName) {
		String[] path = { "", "" };
		int hashCode = fileName.hashCode();
		int dir1 = (hashCode >> 4) & 0xf;
		int dir2 = hashCode & 0xf;
		String newpath = dir + "/" + dir1 + "/" + dir2 + "/";
		File file = new File(newpath);
		if (!file.exists()) {
			file.mkdirs();
		}
		fileName = uuidName(fileName);
		path[0] = newpath + fileName;
		path[1] = "/" + dir1 + "/" + dir2 + "/" + fileName;
		return path;
		// return newpath + uuidName(fileName);
	}
	
	public static String hashNewFile(String fileName){
		int hashCode = fileName.hashCode();
		return hashCode+uuidName(fileName);
	}
	
	
}
